<template>
  <div class="Personal">
    <el-row>
      <el-col :lg="8" style="padding: 10px">
        <el-card class="box-card">
          <el-row style="margin-top: 10px;height: 75px;width: 300px;">
            <el-col :span="7" style="height: 75px;overflow: hidden">
              <el-avatar shape="square" style="width: 75px;height:75px" :src="usreimg?usreimg:imgsrc" fit="contain" ></el-avatar>
            </el-col>
            <el-col :span="17">
              <el-row>
                <el-col :span="24">
                  <span style="font-size: 14px">{{ usermingzi?usermingzi:username }}</span>
                </el-col>
                <el-col :span="24">
                  <small>UID:{{ userid }}</small>
                </el-col>
                <el-col :span="24"  style="display: flex">
                  <div class="nw" style="display: inline-block;margin-right: 10px;position:relative;overflow: hidden">
                    <el-button type="primary" plain style="padding: 2px 10px 2px 2px;border: 0px;line-height: 30px;" @click="gosign">
                      <i class="el-icon-s-claim" style="padding: 5px 8px" v-if="sign"></i>
                      <i class="el-icon-check" style="padding: 5px 8px" v-else></i>
                      {{!sign?'已签到':'签到'}}</el-button>
                    <div class="ddd" v-if="isWx && sign" style="width: 100%;height: 500px;position:absolute;left: 0;top: 0">
                      <wx-open-subscribe template="4zAgApnkvJO-cvKHrbYX5OebHNRflutUDzrX74ueEnA" id="subscribe-btn"
                                         style="position:absolute;width:100%;height:100%;left:0px;top:0px;overflow:hidden;"
                                         @success="openSubscribeSuccess" @error="openSubscribeError">
                        <script type="text/wxtag-template" slot="style">
                          <style>
                            .subscribe-btn { width: 100%; height: 500px;}
                          </style>
                        </script>
                        <script type="text/wxtag-template">
                          <div class="subscribe-btn"></div>
                        </script>
                      </wx-open-subscribe>
                    </div>
                  </div>
                  <el-button type="primary" plain style="padding: 2px 10px 2px 2px;border: 0px;line-height: 30px;" @click="userexit">
                    <i class="glyphicon glyphicon-log-out" style="padding: 5px 8px"></i>退出</el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <br>
          <van-cell icon="gold-coin" :border="false" center >
            <template #title>
              <span class="custom-title">当前余额：<span style="color:#ff0000;">￥{{ useryue }}</span></span>
            </template>
            <template #right-icon>
              <el-link :underline="false" @click="money">
                <span>充值</span>
                <van-icon name="peer-pay" class="peer-pay_icon" />
              </el-link>
            </template>
          </van-cell>
          <van-cell icon="chat" :border="false" center >
            <template #title>
              <span class="custom-title">联系QQ：{{userlxfs}}</span>
            </template>
            <template #right-icon>
              <el-link :underline="false" @click="editlxfs">
                <span>修改</span>
                <van-icon name="edit" class="edit-icon" />
              </el-link>
            </template>
          </van-cell>

          <el-row type="flex" justify="space-between" align="middle" v-if="editLxfsFlag">
            <el-input
                style="width: 180px;"
                placeholder="请输入新的联系方式"
                v-model="newlxfs"
                clearable>
            </el-input>
            <van-button plain hairline type="primary" size="small" @click="editLxfsend">修 改</van-button>
          </el-row>

          <van-cell icon="invitation" :border="false" center >
            <template #title>
              <span class="custom-title">邮箱地址：{{ useremail }}</span>
            </template>
            <template #right-icon>
              <el-link :underline="false" v-if="useremail=='暂未绑定'" @click="$router.push('/bindemail')">
                <span>绑定</span>
                <van-icon name="edit" class="edit-icon" />
              </el-link>
            </template>
          </van-cell>
        </el-card>
      </el-col>
      <el-col :lg="8" style="padding: 10px">
        <el-card class="box-card">
          <!--修改名字-->
          <h4 style="font-size: 18px;font-weight: bold;">昵称设置<br><small style="font-size: 12px">设置一次昵称需要消耗1毛钱。</small></h4>
          <div style="margin-top: 15px;">
            <el-input placeholder="请输入内容" v-model="newname" >
              <template slot="append">
                <el-button type="primary" @click="editName">设置</el-button>
              </template>
            </el-input>
          </div>
        </el-card>
      </el-col>
      <el-col :lg="8" style="padding: 10px">
        <el-card class="box-card">
          <!--头像管理
            1、用户如果不修改 就删除已上传的图片
            2、用户通过修改 删除原图片 保存本次图片
            3、注意图片的上传大小
            4、如果用户上传，上传后后端将图片保存，但是用户并没有点击修改
          -->
          <h4 style="font-size: 18px;font-weight: bold;">头像管理<br><small style="font-size: 12px">头像修改成功后如果没有正常显示，请刷新页面缓存。</small></h4>
          <van-uploader v-model="fileList" preview-size="160px" :after-read="afterRead" :max-size="500 * 1024" :max-count="1" @oversize="onOversize" :before-read="beforeRead" :preview-options="{closeable:true}"/>
          <van-divider dashed/>
          <el-button type="primary" plain size="small" @click="updataTX">修改头像</el-button>
        </el-card>
      </el-col>
    </el-row>
    <div class="wx_bind_pop" v-if="wxpop">
      <div class="wx_bind_pop_main">
        <div class="wx_bind_pop_title">
          <p>未绑定微信，将无法接收消息哦</p>
          <p>点击下方快捷绑定微信</p>
          <p>绑定后将可以使用微信快捷登录</p>
        </div>
        <div class="wx_bind_pop_btn" @click="wxBind">
          <div class="wx_bind_pop_btn_text">
            微信一键绑定
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapState} from "vuex"
import userimg from "@/assets/userAvatar.png"
import qs from "qs";
import {addSurplus, setUserAvatar, setUserName, setUserTel, userWxBind} from "../../utils/api";
export default {
  name: "Personal",
  data(){
    return {
      imgsrc:userimg,
      fileList:[],
      imgfiles:'',
      show:true,
      newlxfs:'',
      editLxfsFlag:false,
      newname:'',
      lxfspattern:/^[1-9][0-9]{4,10}$/,
      userpattern:/^[(a-zA-Z0-9\u4e00-\u9fa5)]{2,8}$/,
      isWx:false,
      wxpop:false,
      qiandao:false
    }
  },
  methods:{
    money(){
      this.$router.push('/user/pay')
    },
    editlxfs(){
      this.editLxfsFlag=true
    },
    editName(){
      if(this.newname){
        if(this.userpattern.test(this.newname)){
          setUserName(qs.stringify({name:this.newname,id:this.userid,yue:this.useryue})).then(respose=>{
            if(respose.status===200){
              this.$store.state.usermingzi=this.newname;
              this.$store.state.useryue=(this.$store.state.useryue-0.1).toFixed(2);
              this.newname="";
              this.$notify({
                title: '昵称修改成功！',
                type: 'success'
              });
            }else{
              this.$notify.error({
                title: '昵称修改失败！',
              });
            }
          }).catch(error=>{
            this.$notify.error({
              title: '昵称修改失败！',
            });
          })
        }else{
          this.$message.error("请输入3-8个字符组成的昵称")
        }
      }else{
        this.$message.error("你还没写新的昵称呢")
      }
    },
    editLxfsend(){
      if(this.newlxfs){
        this.$dialog.confirm({message:'确定修改了吗？'}).then(()=>{
          if(this.lxfspattern.test(this.newlxfs)){
            setUserTel(qs.stringify({id:this.userid,yue:this.useryue,lxfs:this.newlxfs})).then(respose=>{
              if(respose.status===200){
                this.$store.state.userlxfs=this.newlxfs;
                this.editLxfsFlag=false;
                this.$notify({
                  title: '联系方式修改成功！',
                  type: 'success'
                });
              }else{
                this.$notify.error({
                  title: '联系方式修改失败！',
                });
              }
            }).catch(error1=>{
              this.$notify.error({
                title: '联系方式修改失败！',
              });
            })
          }else{
            this.$message.error("请输入正确的QQ号")
          }
        }).catch(()=>{})
      }else{
        this.$message.error("你还没写新的联系方式呢")
      }
    },
    userexit(){
      this.$emit('quickuserhide');
      this.$store.commit('setDlzt');
      this.$toast.success("退出成功");
      this.$router.push("/login");
      localStorage.removeItem("userToken");
    },
    afterRead(file){
      //将图片信息保存，等待用户下一步的操作，如果点击修改就上传到服务器
      this.imgfiles=file.file;
    },
    beforeRead(file){
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('请上传 jpg/png 格式图片');
        return false;
      }
      return true;
    },
    onOversize(file){
      this.$message.error('文件大小不能超过 500kb');
    },
    updataTX(){
      // 此时可以自行将文件上传至服务器
      if(this.fileList.length!==0){
        this.fileList[0].status='uploading';
        this.fileList[0].message='上传中...';
        let data = new FormData();
        data.append("avatar", this.imgfiles); //将图片信息压入表单内
        setUserAvatar(data).then(respose=>{
          if(respose.status===200){
            //this.fileList[0].url = respose.imgpath.replace(/server_management/, '../..');
            this.$store.state.usreimg= respose.imgpath.replace(/public/, 'http://cloud.pinggai8.com');
            this.fileList[0].status='done';
            this.$message.success('修改头像成功');
          }else{
            this.$message.error(respose?.msg || '上传出错，请稍后再试');
          }
        }).catch(error=>{
          console.log(error)
          this.fileList[0].status='failed';
          this.fileList[0].message='上传失败';
        })
      }else{
        this.$message.error('还没有上传头像呢');
      }
    },
    gosign() {
      //如果在微信环境中 那么将被微信标签直接拦截 不能签到 或者 正在签到
      if(!this.sign || this.qiandao){return}
      this.qiandao = true
      addSurplus(qs.stringify({type:5})).then(res=>{
        this.qiandao = false
        if(res?.status == 200){
          this.$store.commit('setSign',false);
          this.$notify.success({
            title:res?.msg,
            message:`获得奖励￥${res?.body}元`
          })
        }else{
          this.$notify.error({
            title:'每日奖励活动——警告',
            message:res?.msg,
          })
        }
      }).catch(err=>{
        console.log(err)
      })
    },
    openSubscribeSuccess(v){
      if(!this.sign || this.qiandao){return}
      this.qiandao = true
      let status = JSON.parse(JSON.parse(v.detail.subscribeDetails)['4zAgApnkvJO-cvKHrbYX5OebHNRflutUDzrX74ueEnA']).status
      if(status == 'accept'){
        //发送增加
        addSurplus(qs.stringify({type:5,m_id:'4zAgApnkvJO-cvKHrbYX5OebHNRflutUDzrX74ueEnA'})).then(res=>{
          this.qiandao = false
          if(res?.status == 160){
            this.wxpop = true
            return
          }
          if(res?.status == 200){
            this.$store.commit('setSign',false);
            this.$notify.success({
              title:res?.msg,
              message:`获得奖励￥${res?.body}元`
            });
          }else{
            this.$notify.error({
              title:'每日奖励活动——警告',
              message:res?.msg,
            });
          }
        }).catch(err=>{
          console.log(err)
        })
      }else if(status == 'reject'){
        //用户取消
        this.gosign()
      }else{
        this.gosign()
      }
    },
    openSubscribeError(v){
      //用户拒绝弹框
      this.gosign()
    },
    wxBind(){
      window.location.replace("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx325d8a04a600270c&redirect_uri="+window.location.origin+'/user/personal' +
          "&response_type=code&scope=snsapi_userinfo&state=cc#wechat_redirect")
    }
  },
  computed:{
    ...mapState([
      "userid","useryue","userlxfs","username","usermingzi","usreimg", 'sign','useremail',
    ])
  },
  created() {
    let ua = navigator.userAgent.toLowerCase();
    if(ua.indexOf('micromessenger') != -1){
      this.isWx=true
    }else{
      return
    }

    /*如果存在code 并且用户已经登录 是微信环境 则是微信绑定事件*/
    if(this.$route.query.code && localStorage.getItem('userToken') && this.isWx){
      userWxBind(qs.stringify({code:this.$route.query.code})).then(res=>{
        delete this.$route.query.code;
        if(res.status==200){
          this.$notify.success({
            title: '温馨提示',
            message: res.msg
          });
        }else{
          this.$notify.error({
            title: '温馨提示',
            message: res.msg
          });
        }
      }).catch(err=>{
        console.log(err)
      })
    }
  }
}
</script>

<style scoped>
.van-cell{
  padding: 10px 0px;
}
.edit-icon,.peer-pay_icon{
  margin-left: 5px;
}
.van-divider--hairline{
  margin: 0 0 5px;
}
.wx_bind_pop{
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.25);
}
.wx_bind_pop_main{
  width: 50%;
  min-width: 300px;
  background: #ffffff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border-radius: 10px;
  box-shadow: 6px 4px 10px rgba(0, 0, 0, 0.4);
}
.wx_bind_pop_title{

}
.wx_bind_pop_title p{
  padding: 0;
  margin: 10px 0 0 0;
  text-align: center;
  font-size: 4vw;
}
.wx_bind_pop_btn{
  width: 80%;
  height: 50px;
  background: #0CD55F url("../../assets/wxbind.png") calc(50% - 60px) 50%/40px 40px no-repeat;
  padding-left: 32%;
  margin: 20px auto;
  border-radius: 8px;
}
.wx_bind_pop_btn_text{
  font-size: 16px;
  color: white;
  width: 120px;
  line-height: 50px;
  white-space: nowrap;
}
</style>
